package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;


    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //获取日期集合
        List<LocalDate> timeList = getLocalDates(begin, end);

        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : timeList) {
            //查询date日期对应的营业额：状态已完成的订单合计
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);


            //select sum(amount) from orders where order_time > begin and order_time < end and status = 5;
            Map map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", 5);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        //封装返回结构
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(timeList, ","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }



    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> localDates = getLocalDates(begin, end);

        List<Integer> userList1 = new ArrayList<>();
        List<Integer> userList2 = new ArrayList<>();
        for (LocalDate localDate : localDates) {
            //查询date日期对应新增用户
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            Map map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);

            Integer user = userMapper.countByUserId(map);
            user = user == null ? 0 : user;
            userList1.add(user);

            //查看用户总数
            Map userMap = new HashMap();
            userMap.put("end", endTime);
            Integer sumUser = userMapper.countByUserId(userMap);
            sumUser = sumUser == null ? 0 : sumUser;
            userList2.add(sumUser);
        }


        return UserReportVO.builder()
                .dateList(StringUtils.join(localDates, ","))
                .totalUserList(StringUtils.join(userList2, ","))
                .newUserList(StringUtils.join(userList1, ","))
                .build();
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> localDates = getLocalDates(begin, end);

        List<Integer> orderList1 = new ArrayList<>();
        List<Integer> orderList2 = new ArrayList<>();
        for (LocalDate localDate : localDates) {
            //查询date日期对应订单数
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            //查的是那一天的订单总数
            Integer count1 = getOrderCount(beginTime,endTime,null);
            count1 = count1 == null ? 0 : count1;
            orderList1.add(count1);

            //查的是那一天有效的订单总数
            Integer count2 = getOrderCount(beginTime,endTime, Orders.COMPLETED);
            count2 = count2 == null ? 0 : count2;
            orderList2.add(count2);

        }
        //求订单总数
        Integer totalOrderCount = orderList1.stream().reduce(Integer::sum).get();
        //有效订单数
        Integer ValidOrderCount = orderList2.stream().reduce(Integer::sum).get();
        //计算订单完成率
        Double OrderCompletionRate = 0.0;
        if (totalOrderCount != 0){
            OrderCompletionRate = ValidOrderCount.doubleValue() / totalOrderCount;
        }

        return OrderReportVO.builder()
                .dateList(StringUtils.join(localDates,","))
                .orderCompletionRate(OrderCompletionRate)
                .orderCountList(StringUtils.join(orderList1,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(ValidOrderCount)
                .validOrderCountList(StringUtils.join(orderList2,","))
                .build();
    }

    /**
     * 查询销量排名前十
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        //根据时间查找订单销量前十
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime,endTime);
        //list里面的数据单项拿出来，然后重新组成一个集合
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(names,","))
                .numberList(StringUtils.join(numbers,","))
                .build();
    }

    //获取订单数
    private Integer getOrderCount(LocalDateTime begin, LocalDateTime end, Integer status){
        Map map = new HashMap<>();
        map.put("begin",begin);
        map.put("end",end);
        map.put("status",status);
        return orderMapper.countById(map);
    }

    //获取前端返回的日期造成一个日期集合
    private List<LocalDate> getLocalDates(LocalDate begin, LocalDate end) {
        List<LocalDate> timeList = new ArrayList<>();
        timeList.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            timeList.add(begin);
        }
        return timeList;
    }

    /**
     * 导出运营数据表表
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        //1、查询数据库：数据为近30天的数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now();

        //查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

        //2、通过POI将数据数据写到Excel文件
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于模版文件创建一个新的excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //填充统一的时间
            XSSFSheet sheet = excel.getSheetAt(0);
            sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);

            //第4行
            XSSFRow row = sheet.getRow(3);
            //营业额  第4行。第3个单元格
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            //订单完成率 第4行。第5个单元格
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            //新增用户数 第4行。第7个单元格
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //第五行
            row = sheet.getRow(4);
            //有效订单 第5行。第3个单元格
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            //平均客单价 第5行。第5个单元格
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

//            获取时间，以便后面填充数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                //查询莫一天的营业数据
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                XSSFRow row1 = sheet.getRow(7 + i);
                row1.getCell(1).setCellValue(date.toString());
                row1.getCell(2).setCellValue(businessData.getTurnover());
                row1.getCell(3).setCellValue(businessData.getValidOrderCount());
                row1.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row1.getCell(5).setCellValue(businessData.getUnitPrice());
                row1.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //3、通过输出流将文件下载到客户端
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
